import { View, Text, Image, Input } from '@tarojs/components'
import './index.scss'
import CloudIcons from '@/assets/ImageUrlConfig'
import { useDispatch, useSelector } from 'react-redux'
import { useDidShow, setStorageSync, navigateBack, cloud } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { GetArticleApi, GetSpaceApi, SearchArticleApi } from '@/api/index.js'

export default function Search() {
	const dispatch = useDispatch()
	const userStore = useSelector((state) => state.user)
	const spaceStore = useSelector((state) => state.space)
	const recentStore = useSelector((state) => state.recent)
	const articleStore = useSelector((state) => state.article)

	const cloneDeep = (obj) => JSON.parse(JSON.stringify(obj))

	let timer

	const [searchResult, setSearchResult] = useState({})
	const [recentClone, setRecentClone] = useState({})
	const [renderList, setRenderList] = useState({})
	const [isSearch, setIsSearch] = useState(false)

	useDidShow(() => {
		initRecentClone()
	})

	useEffect(() => {
		updateRecentClone()
	}, [recentStore])

	useEffect(() => {
		if (isSearch) {
			setRenderList(searchResult)
		} else {
			setRenderList(recentClone)
		}
	}, [isSearch])

	const initRecentClone = () => {
		const clone = cloneDeep(recentStore)
		Object.keys(clone).forEach((key) => {
			clone[key].show = true
		})
		setRecentClone({})
		setRenderList({})
		setRecentClone(clone)
		setRenderList(clone)
	}

	const updateRecentClone = () => {
		setRecentClone({})
		const clone = cloneDeep(recentStore)
		Object.keys(clone).forEach((key) => {
			clone[key].show = true
		})
		setRecentClone(clone)
	}

	const triggleCatlog = (key) => {
		const clone = cloneDeep(renderList)
		clone[key].show = !clone[key].show
		setRenderList(clone)
	}

	const clearRecent = () => {
		setStorageSync('recent-read-article', {})
		dispatch({
			type: 'UPDATE_RECENT',
			payload: {},
		})
	}

	const viewThisArticle = async (spaceid, articleid) => {
		if (spaceid !== spaceStore._id) {
			const space = await GetSpaceApi({ id: spaceid })
			dispatch({
				type: 'UPDATE_SPACE',
				payload: space,
			})
		}
		if (articleid !== articleStore._id) {
			const article = await GetArticleApi({ id: articleid })
			dispatch({
				type: 'UPDATE_ARTICLE',
				payload: article,
			})
		}
		navigateBack({
			delta: 1,
		})
	}

	const search = (e) => {
		clearTimeout(timer)
		timer = setTimeout(() => {
			const title = e.detail.value.trim()
			if (!title) {
				setSearchResult({})
				setIsSearch(false)
				return
			}
			SearchArticleApi({
				title,
			}).then((articles) => {
				setIsSearch(true)
				let searchRes = {}
				articles.forEach((article) => {
					const spaceid = article.belong_space
					if (searchRes[spaceid]) {
						searchRes[spaceid].children.push(article)
					} else {
						const belongSpace = userStore.space.find((sapce) => sapce._id === spaceid)
						searchRes[spaceid] = {
							show: true,
							name: belongSpace.name,
							children: [article],
						}
					}
				})
				setSearchResult({})
				setSearchResult(searchRes)
			})
		}, 0.5 * 1000)
	}

	return (
		<View className='search'>
			<View className='input-warp'>
				<Image className='icon' src={CloudIcons.search2}></Image>
				<Input
					className='input'
					type='text'
					placeholder='在张之洞的UE中搜索'
					focus
					onInput={search}
					onConfirm={search}
				></Input>
			</View>
			{isSearch ? null : (
				<View className='recent-view'>
					<Text>最近浏览</Text>
					<Text className='clear' onTap={clearRecent}>
						清除
					</Text>
				</View>
			)}
			{Object.keys(renderList).map((key) => {
				return (
					<View className='recents'>
						<>
							<View
								className='catlog'
								onTap={() => {
									triggleCatlog(key)
								}}
							>
								<Text className='name'>{renderList[key].name}</Text>
								<Image className={renderList[key].show ? 'img' : 'img shrink'} src={CloudIcons.spread}></Image>
							</View>
							<View className={renderList[key].show ? 'files' : 'files hide'}>
								{renderList[key].children.map((article) => (
									<View
										className='file'
										onTap={() => {
											viewThisArticle(key, article._id)
										}}
									>
										{article.title}
									</View>
								))}
							</View>
						</>
					</View>
				)
			})}
		</View>
	)
}
